import { Button, Divider, Flex, Table, Upload, Spin, Space, Modal, Form, Input, notification, Dropdown, Radio } from 'antd'
import { ExclamationCircleFilled, DownOutlined } from '@ant-design/icons';
import { useState } from 'react';
import './views.css'
import * as XLSX from 'xlsx';
import axios from 'axios';
const { confirm } = Modal
const { Column } = Table;


export default function LearnAnt() {
    // #region 变量
    const [columns, setColumns] = useState([]);
    const [tableData, setTableData] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [loading, setLoading] = useState(false);
    const [pageLoading, setPageLoading] = useState(false);
    const [editingRecord, setEditingRecord] = useState(null);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isOpen, setIsOpen] = useState(false)
    const [isOpen1, setIsOpen1] = useState(false)
    const [inputLabel, setInputLabel] = useState([]);
    const [form] = Form.useForm();
    const [form1] = Form.useForm();
    const [form2] = Form.useForm();
    // #endregion

    //操作提示
    const [api, contextHolder] = notification.useNotification();
    const openNotification = (text) => {
        api['success']({
            message: '操作提示',
            description: `${text}`,
            duration: 2,
            placement: 'top'
        });
    };

    const openNotification1 = (text) => {
        api['error']({
            message: '操作提示',
            description: `${text}`,
            duration: 3,
            placement: 'top'
        });
    };

    // #region 全选批量删除
    const batchDelete = () => {
        setLoading(true);
        selectedRowKeys.sort((a, b) => b - a); // 对索引数组进行降序排序，避免删除数据后索引发生变化
        console.log('selectedRowKeys', selectedRowKeys)
        setTableData(prevTableData => {
            return prevTableData.filter((item, index) => {
                return !selectedRowKeys.includes(item.key);
            });
        });
        openNotification("删除")
        setTimeout(() => {
            setSelectedRowKeys([]);
            setLoading(false);
        }, 1000);

    };
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    // #endregion


    // #region 导入接口数据
    const importApiData = (values) => {
        console.log("接口数据", values)
        if (values.url === undefined) {
            openNotification1("url为空，无法导入！")
        } else {
            if (values.methods === "GET") {
                axios({
                    method: values.methods,
                    url: values.url,
                    params: values.parameter ? JSON.parse(values.parameter) : {}
                }).then((res => {
                    console.log(res.data)
                    const data = res.data.data.data
                    //判断数据是否符合格式
                    if (Array.isArray(data) && data.length > 0 && typeof data[0] === 'object') {
                        // data是对象数组
                        const keysArray = Object.keys(data[0]);
                        const columnsData = keysArray.map((item, index) => <Column title={item} dataIndex={item} key={index} />)
                        setColumns(columnsData)
                        const dataArray = data.map((obj, index) => {
                            obj.key = index
                            return obj
                        })
                        setTableData(dataArray)
                        setInputLabel(keysArray)

                    } else {
                        // data不是对象数组
                        openNotification1("接口返回的数据不是对象数组无法导入")
                    }

                })).catch(err => {
                    // 处理错误
                    openNotification1("请求失败")
                    console.error(err);
                })
            } else {
                axios({
                    method: values.methods,
                    url: values.url,
                    data: values.parameter ? JSON.parse(values.parameter) : {}
                }).then((res => {
                    console.log(res.data)
                    const data = res.data
                    //判断数据是否符合格式
                    if (Array.isArray(data) && data.length > 0 && typeof data[0] === 'object') {
                        // data是对象数组
                        const keysArray = Object.keys(data[0]);
                        const columnsData = keysArray.map((item, index) => <Column title={item} dataIndex={item} key={index} />)
                        setColumns(columnsData)
                        const dataArray = data.map((obj, index) => {
                            obj.key = index
                            return obj
                        })
                        setTableData(dataArray)
                        setInputLabel(keysArray)

                    } else {
                        // data不是对象数组
                        openNotification1("接口返回的数据不是对象数组无法导入")
                    }
                })).catch(err => {
                    // 处理错误
                    openNotification1("请求失败")
                    console.error(err);
                })
            }
        }

        form1.resetFields()

    }

    const onCancel = () => {
        setIsOpen(false)
        form1.resetFields();
    }

    const onCancel1 = () => {
        setIsOpen1(false)
        form2.resetFields();
    }

    const openModel = () => {
        setIsOpen(true)
    }
    const openModel1 = () => {
        setIsOpen1(true)
    }

    // #endregion

    //上传excel表格
    const uploadProps = {
        beforeUpload: (file) => {
            setPageLoading(true)
            importFromExcel(file);
            return false;
        },
        showUploadList: false, // 隐藏上传列表
    };

    const menuProps = {
        items: [
            {
                label: (<Upload {...uploadProps}>
                    <Button type="primary" >导入Excel数据</Button>
                </Upload>),
                key: '1',
            },
            {
                label: (<Button type="primary" onClick={openModel}>导入接口数据</Button>),
                key: '2',
            }
        ]

    }
    // 导入Excel数据
    const importFromExcel = (file) => {

        const reader = new FileReader();
        reader.onload = (e) => {
            const data = e.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            const importedData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            //处理导出来的数据 
            const keys = importedData[0];
            const columnsData = keys.map((item, index) => <Column title={item} dataIndex={item} key={index} />)
            const formattedData = importedData.slice(1).map((row, index) => {
                return keys.reduce((obj, key, i) => {
                    obj[key] = row[i];
                    return obj;
                }, { key: index });
            });

            setTableData(formattedData);
            setColumns(columnsData)
            setInputLabel(keys)
            setPageLoading(false)
        };
        reader.readAsBinaryString(file);
    };

    // 导出数据
    const exportToExcel = () => {
        if (tableData.length > 0) {
            const newTableData = tableData.map((obj) => {
                const { key, ...rest } = obj
                return rest
            })
            const worksheet = XLSX.utils.json_to_sheet(newTableData);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
            XLSX.writeFile(workbook, 'xlsx_data.xlsx');
        } else {
            openNotification1("数据为空，无法导出！")
        }

    };

    // 删除
    const deleteTableData = (key) => {
        confirm({
            title: 'Do you Want to delete these items?',
            icon: <ExclamationCircleFilled />,
            content: 'Some descriptions',
            onOk() {
                const newItems = tableData.filter((item) => item.key !== key);
                setTableData(newItems);
                openNotification("删除成功！")

            },
            onCancel() {
                console.log('Cancel');
            },
        });

    }

    //编辑数据
    const editTableData = (record) => {
        form.setFieldsValue(record)
        setEditingRecord(record)
        setIsModalVisible(true);

    }

    // 编辑确认
    const handleModalOk = () => {
        const newData = tableData.map(item => {
            if (item.key === editingRecord.key) {
                console.log("item", item)
                console.log("editingRecord", editingRecord)
                return editingRecord;
            }
            return item;
        });
        setTableData(newData);
        setIsModalVisible(false);
        openNotification('修改成功！')
    };
    //编辑取消
    const handleModalCancel = () => {
        setIsModalVisible(false);
    };

    //保存数据库
    function exportToMySql(values) {

        if (tableData.length > 0) {
            console.log(tableData)
            const tableDataString = JSON.stringify(tableData)
            axios.post('http://localhost:8888/users/save', { tableName: values.tableName, tableDataString: tableDataString }).then((res) => {
                if (res.data.success) {
                    openNotification(res.data.msg)
                } else {
                    openNotification1(res.data.msg)
                }
            }).catch(err => {
                console.log(err)
                openNotification1("请求错误！")
            })
        } else {
            openNotification1("数据为空，无法导入！")
        }

    }
    //接口导入确认
    const apiModalOk = () => {
        form1
            .validateFields()
            .then((values) => {
                importApiData(values);
                form1.resetFields();
            })
            .catch((info) => {
                console.log('Validate Failed:', info);
            });

        setIsOpen(false)
    }

    //数据库导入确认
    const mysqlModalOk = () => {
        form2
            .validateFields()
            .then((values) => {

                exportToMySql(values);
                form2.resetFields();
            })
            .catch((info) => {
                console.log('Validate Failed:', info);
            });

        setIsOpen1(false)
    }

    return (
        <div>
            {contextHolder}
            <Divider className='LineWord'>Ant-Design Table</Divider>
            <Flex gap='large' justify='flex-start' align="center" horizontal='true'>
                <Button type="primary" onClick={batchDelete} disabled={!hasSelected} loading={loading}>
                    批量删除
                </Button>

                <Dropdown menu={menuProps}>
                    <Button type="primary" >
                        <Space>
                            导入数据
                            <DownOutlined />
                        </Space>
                    </Button>
                </Dropdown>

                <Button onClick={exportToExcel} type="primary">导出Excel</Button>
                <Button onClick={openModel1} type="primary">导入数据库</Button>
            </Flex>
            <div style={{ marginTop: 20 }}>
                <Spin size="large" tip='Loading' spinning={pageLoading} >
                    <Table rowSelection={rowSelection} dataSource={tableData}>
                        {columns}
                        {tableData.length > 0 ? (<Column
                            title="Action"
                            key="action"
                            render={(_, record) => (
                                <Space size="middle">
                                    <Button onClick={() => editTableData(record)}>Edit</Button>
                                    <Button onClick={() => deleteTableData(record.key)} danger>Delete</Button>
                                </Space>
                            )}
                        />) : null}
                    </Table>
                </Spin>
                <Modal
                    title="编辑数据"
                    open={isModalVisible}
                    onOk={handleModalOk}
                    onCancel={handleModalCancel}
                >
                    <Form
                        labelCol={{ span: 8 }}
                        form={form}
                        wrapperCol={{ span: 16 }}
                        onValuesChange={(changedValues, allValues) => {
                            console.log('changedValues', changedValues)
                            console.log('allValues', allValues)
                            setEditingRecord({ ...editingRecord, ...changedValues });
                            // console.log("值改变", editingRecord)
                        }}
                    >
                        {inputLabel.map((item, index) => (<Form.Item label={item} name={item} key={index}>
                            <Input />
                        </Form.Item>))}
                    </Form>
                </Modal>

                <Modal
                    open={isOpen}
                    title="导入接口数据"
                    okText="导入"
                    cancelText="取消"
                    onCancel={onCancel}
                    onOk={apiModalOk}
                >
                    <Form
                        form={form1}
                        layout="vertical"
                    >
                        <Form.Item
                            name="url"
                            label="接口地址"
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item name="parameter" label="参数（json格式）">
                            <Input type="textarea" />
                        </Form.Item>
                        <Form.Item name="methods" label="请求方式" initialValue="GET">
                            <Radio.Group>
                                <Radio value="GET">Get</Radio>
                                <Radio value="POST">Post</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </Form>
                </Modal>

                <Modal
                    open={isOpen1}
                    title="导入数据库"
                    okText="导入"
                    cancelText="取消"
                    onCancel={onCancel1}
                    onOk={mysqlModalOk}
                >
                    <Form
                        form={form2}
                        layout="vertical"
                    >
                        <Form.Item
                            name="tableName"
                            label="表名"
                        >
                            <Input />
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    )
}
